﻿using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;

namespace Learning
{
    public class Volume_ColorIntensityRenderPass : ScriptableRenderPass
    {
        public Volume_ColorIntensitySetting setting;

        public override void OnCameraSetup(CommandBuffer cmd, ref RenderingData renderingData)
        {
        }

        public override void Configure(CommandBuffer cmd, RenderTextureDescriptor cameraTextureDescriptor)
        {
        }

        public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
        {
#if UNITY_EDITOR
            // 如果不希望 Scene 窗口下执行该Pass（只有Game执行，避免影响Scene窗口下查看），可以添加这个检测排查掉 SceneCamera（该摄像机是Scene窗口的相机，是看不见的）
            // 也可以通过判定其它相机来做剔除，不过一般来说摄像机可以选择自己的Renderer，所以这里的判定一般用于排除 SceneCamera
            if (renderingData.cameraData.isSceneViewCamera)
            {
                return;
            }
#endif

            if (setting.material == null)
            {
                return;
            }

            RenderTextureDescriptor rt = new RenderTextureDescriptor(Camera.main.pixelWidth, Camera.main.pixelHeight, RenderTextureFormat.Default, 0);
            RenderTexture rtTex = RenderTexture.GetTemporary(rt);
            
            RenderTargetIdentifier cameraColorTexture = renderingData.cameraData.renderer.cameraColorTarget;

            CommandBuffer cmd = CommandBufferPool.Get(name: "ColorIntensityRenderPass");

            
            // 从全局Volume中获取我们需要的配置，如果没有Override配置，是可以直接获取到默认值的，不需要判空
            var stack = VolumeManager.instance.stack;
            var volume = stack.GetComponent<ColorIntensityVolumeComponent>();
            // 设定参数
            setting.material.SetFloat("_Intensity", volume.intensity.value);
            setting.material.SetColor("_Color", volume.color.value);
            
            Blit(cmd, cameraColorTexture, rtTex, setting.material);
            Blit(cmd, rtTex, cameraColorTexture);

            context.ExecuteCommandBuffer(cmd);
            cmd.Clear();
            CommandBufferPool.Release(cmd);
        }

        public override void OnCameraCleanup(CommandBuffer cmd)
        {
        }
    }
}
